package control.client;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import control.server.FilmesControl;

/**
 * Servlet implementation class FilmeServlet
 */
public class FilmeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private FilmesControl control;
	
    public FilmeServlet() {
        super();
		try {
			control = new FilmesControl();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//
		
		try {
			String opcao = request.getParameter("opcao");
			
			if (opcao.isEmpty()){
				request.getSession().setAttribute("filmesDestaque", control.listaDestaque());
				request.getRequestDispatcher("/index.jsp").forward(request, response);
			}
			
			if (opcao.equalsIgnoreCase("iniciar")){
				request.getSession().setAttribute("filmesDestaque", control.listaDestaque());
				request.getRequestDispatcher("/destaques.jsp").forward(request, response);
				
			}else if (opcao.equalsIgnoreCase("paginacao")){
				
				int pag = Integer.parseInt(request.getParameter("pag"));
				int filmes_por_pag = 6;
				int total = control.total();
				
				int num_total_paginas = (int) ((total%filmes_por_pag==0) ? total/filmes_por_pag : Math.floor(total/filmes_por_pag)+1);
				
				int ant = pag -1;
				int pos = pag +1;
				
				if (ant == 0) ant = 1;
				if (pos > num_total_paginas) pos = num_total_paginas;
				
				request.getSession().setAttribute("ant", ant);
				request.getSession().setAttribute("pos", pos);
				
				int inicio = (pag * filmes_por_pag) - filmes_por_pag;
				
				request.getSession().setAttribute("novidades",control.lista("data_lanc_filme", inicio, filmes_por_pag));
				request.getRequestDispatcher("/paginacao.jsp").forward(request, response);
				
			}else if (opcao.equalsIgnoreCase("trailer")){
				request.getSession().setAttribute("filme",control.filmeId(Integer.parseInt(request.getParameter("id"))));
				request.getRequestDispatcher("/trailer.jsp").forward(request, response);
				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	
	}

}
